package com.gs.m_order_list

import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.gs.common.BaseCompatActivity
import com.gs.common.data.Order
import com.gs.common.global.GlobalVariables
import com.gs.common.util.ActionBarUtil
import com.gs.common.util.DialogUtil
import com.gs.common.util.ToastUtil
import com.gs.m_order_list.adapter.OrderListAdapter
import com.gs.m_order_list.databinding.OrderListLayoutBinding
import java.util.Calendar


class OrderListActivity: BaseCompatActivity(), OrderListPersistent.OnGetOrdersInfoStateCallback {

    private lateinit var binding: OrderListLayoutBinding
    private val mCalendar by lazy { Calendar.getInstance() }
    private val orderListPersistent by lazy { OrderListPersistent.getInstance(this) }
    private val mOrderList = ArrayList<Order>()
    private val mLoginUser = GlobalVariables.loginUser

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.order_list_layout)

        binding.loadingTv.visibility = View.VISIBLE
        binding.orderList.visibility = View.GONE

        // 设置自定义action bar
        ActionBarUtil.setCustomActionBar(this, R.layout.order_list_actionbar_layout)

        // 设置返回按键
        val backBtn = findViewById<ImageView>(R.id.back_btn)
        backBtn.setOnClickListener {
            finish()
        }

        // 设置日历按键
        val exitModeBtn = findViewById<ImageView>(R.id.exit_mode_btn)
        val calendarBtn = findViewById<ImageView>(R.id.calendar_btn)
        val dateSetListener = OnDateSetListener { view, year, month, dayOfMonth ->
            if (mLoginUser == null){
                ToastUtil.showShortToast(this, "按日期查询订单失败")
                return@OnDateSetListener
            }
            exitModeBtn.visibility = View.VISIBLE
            calendarBtn.visibility = View.GONE
            // 处理用户选择的日期
            val date = "$year/${month + 1}/$dayOfMonth"
            // 根据date查询order
            orderListPersistent.getPaidOrdersInfo(mLoginUser.userName, date,this)
        }
        val datePickerDialog = DatePickerDialog(this,0, dateSetListener, mCalendar[Calendar.YEAR], mCalendar[Calendar.MONTH], mCalendar[Calendar.DATE])
        calendarBtn.setOnClickListener {
            datePickerDialog.show()
        }
        exitModeBtn.setOnClickListener {
            exitModeBtn.visibility = View.GONE
            calendarBtn.visibility = View.VISIBLE
            // 查询全部订单
            updateOrderListData()
        }
    }

    override fun onResume() {
        super.onResume()
        // 配置 order list recyclerView
        val layoutManager = LinearLayoutManager(this)
        binding.orderList.layoutManager = layoutManager
        val adapter = OrderListAdapter(this, mOrderList)
        binding.orderList.adapter = adapter

        // 显示order list，不显示加载数据中
        binding.loadingTv.visibility = View.GONE
        updateOrderListData()
        binding.orderList.visibility = View.VISIBLE

        adapter.setOrderListItemDeleteBtnClickListener(object : OrderListAdapter.OnOrderListItemDeleteBtnClickListener{
            override fun onClick(position: Int, orderId: Int) {
                val alertDialog = DialogUtil.createCommonAlertDialog(this@OrderListActivity, "删除", "这个订单") {
                    if (it == DialogUtil.CONFIRM_TO_DO) {
                        orderListPersistent.deleteOrder(orderId, object : OrderListPersistent.OnDeleteOrderStateCallback{
                            override fun onDeleteOrderSuccess() {
                                updateOrderListData()
                                ToastUtil.showShortToast(this@OrderListActivity, "删除订单成功")
                            }

                            override fun onDeleteOrderFailed() {
                                ToastUtil.showShortToast(this@OrderListActivity, "删除订单失败")
                            }

                            override fun onNetworkError() {
                                ToastUtil.showShortToast(this@OrderListActivity, "无法连接网络！")
                            }

                            override fun onServerError() {
                                ToastUtil.showShortToast(this@OrderListActivity, "无法连接服务器！")
                            }
                        })
                    }
                }
                alertDialog.show()
            }
        })

        adapter.setOrderListItemClickListener(object : OrderListAdapter.OnOrderListItemClickListener{
            override fun onItemClick(position: Int, orderId: Int) {
                ToastUtil.showShortToast(this@OrderListActivity, "点击 $orderId")
            }

        })
    }

    private fun updateOrderListData() {
        if (mLoginUser == null) {
            ToastUtil.showShortToast(this, "订单列表更新失败")
            return
        }
        mOrderList.clear()
        orderListPersistent.getPaidOrdersInfo(mLoginUser.userName, null,this)
    }

    override fun onGetOrdersInfoSuccess() {
        val orderDataList = GlobalVariables.orderDataList
        if (orderDataList == null) {
            ToastUtil.showShortToast(this@OrderListActivity, "订单列表更新失败")
            return
        }
        if (orderDataList.isEmpty()) {
            binding.emptyOrderListTv.visibility = View.VISIBLE
        } else {
            binding.emptyOrderListTv.visibility = View.GONE
        }
        mOrderList.clear()
        for (order in orderDataList) {
//            for (orderDetail in order.orderDetailsList) {
//                orderDetail.goods.picture_path = "http:/${API.IP}:${API.PORT}${orderDetail.goods.picture_path }"
//            }
            mOrderList.add(order)
        }
        binding.orderList.adapter?.notifyDataSetChanged()
    }

    override fun onGetOrdersInfoFailed() {
        ToastUtil.showShortToast(this@OrderListActivity, "订单列表更新失败")
    }

    override fun onNetworkError() {
        ToastUtil.showShortToast(this@OrderListActivity, "无法连接网络！")
    }

    override fun onServerError() {
        ToastUtil.showShortToast(this@OrderListActivity, "无法连接服务器！")
    }
}